<!-- 如果需要嵌套多层菜单，用函数组件更合适，可查看Nav.js -->
<template>
  <el-menu default-active="1" theme="dark" @select="onSelect" >
    <template v-for="(item, index) in navs">
      <el-menu-item 
        v-if="!item.children" 
        :index="index + ''" 
        :key="index"
      >
        <i :class="item.iconClass"></i>
        {{ item.name }}
      </el-menu-item>
      <el-submenu 
        v-else 
        :index="index + ''" 
        :key="index"
      >
        <template slot="title">
          <i :class="item.iconClass"></i>
          {{ item.name }}
        </template>
        <el-menu-item 
          v-for="(child, i) in item.children"
          :index="index + '-' + i"
          :key="index + '-' + i"
        >
          {{ child.name }}
        </el-menu-item>
      </el-submenu>
    </template>
  </el-menu>
</template>

<script>
export default {
  name: 'Nav',
  props: {
    navs: {
      type: Array,
      required: true
    }
  },
  methods: {
    onSelect (curIndex, indexArr) {
      let navItem = this.navs
      let indexs

      // 确保不论路由嵌套多深都可以正确取到path
      indexArr.forEach((item, index) => {
        indexs = item.split('-')
        // '+' 隐式转换为number
        navItem = navItem[+indexs[index]].children || navItem[+indexs[index]]
      }, this)

      this.$emit('click', navItem.path)
    }
  }
}
</script>
